package com.zut.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zut.mapper.FileMapper;
import com.zut.mapper.LinkMapper;
import com.zut.pojo.Link;
import com.zut.pojo.QrFile;
import com.zut.pojo.Result;
import com.zut.service.FileService;
import com.zut.service.impl.FileServiceImpl;
import com.zut.utils.UserUtil;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @author: Mr.Liu
 * @create: 2021-11-23 16:11
 */
@RestController
public class FileController {
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    FileMapper fileMapper;

    @Autowired
    UserUtil userUtil;

    @Autowired
    LinkMapper linkMapper;

    @Autowired
    FileService fileService;

    @ApiOperation("文件上传生成二维码")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Result uploadFile(@RequestParam("file")  MultipartFile file,HttpServletRequest request) {
        String fileName = file.getOriginalFilename();//获取文件名
        //生成一个uuid对应一个文件
        String idName = UUID.randomUUID() + fileName;
        String filepath = getUploadPath();
        System.out.println(fileName);
        if (!file.isEmpty()) {
            Integer uuid = userUtil.getUserId(request);
            if (uuid==null){
                uuid = 0;
            }
            logger.info("定制次链接的用户是：{}", uuid);

            //存到数据库中
            fileMapper.insert(new QrFile(idName,uuid,0,fileName));


            try (BufferedOutputStream out = new BufferedOutputStream(
                    new FileOutputStream(new java.io.File(filepath + java.io.File.separator + fileName)))) {
                out.write(file.getBytes());
                out.flush();
                return Result.success("文件上传成功！",fileName);
            } catch (FileNotFoundException e) {
                return Result.error("上传文件失败 FileNotFoundException：");
            } catch (IOException e) {
                return Result.error("上传文件失败 IOException：");
            }
        } else {
            return Result.error("上传文件失败，文件为空");
        }
    }


    /**
     * 获取当前系统路径
     */
    private String getUploadPath() {
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (!path.exists()) path = new File("");
        File upload = new File(path.getAbsolutePath(), "/upload/");
        if (!upload.exists()) upload.mkdirs();
        return upload.getAbsolutePath();
    }


    @ApiOperation("扫描二维码下载")
    @GetMapping("/download/{id}")
    public String downloadFile(@PathVariable String id, HttpServletResponse response) {
        if (id != null) {
            QrFile fid = fileMapper.selectOne(new QueryWrapper<QrFile>().eq("id", id));
            if (fid==null){
                return "没有这个文件";
            }
            fileMapper.updateById(new QrFile(id,null,(fid.getNum()+1),null));
            //设置文件路径
            File file = new File("./upload/"+fid.getId());
            //File file = new File(realPath , fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fid.getId());// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally { // 做关闭操作
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }


    @ApiOperation("返回当前用户所有创建的文件")
    @GetMapping("/file/user/all")
    public Result findAllFilesByUserId(HttpServletRequest request){
        return fileService.findFilesByUser(request);
    }
}
